<?php

namespace App\Modules\Admin\Http\Controllers;

use App\Models\Admin;
use App\Models\Role;
use App\Modules\Admin\Http\Requests\AdminCreateRequest;
use App\Modules\Admin\Http\Requests\AdminUpdateRequest;
use App\Modules\Admin\Http\Controllers\BaseController;
use Illuminate\Support\Facades\Cache;
use App\Services\Admin\UserService;
use Illuminate\Http\Request;


class UserController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $param = $this->getParam('User','User/getList');
        echo 9999999;
        return view('admin::user.index',compact('param'));
    }

    /**
     * 获取列表页
     * @param Request $request
     * @method getList
     * @author chengzhigang<1256699215@qq.com>
     */
    public function getList(Request $request){
        Cache::forever('User/getList', $request->server->get('QUERY_STRING'));
        $page = $request->input('page', 1);
        $per_page = $request->input('limit', 10);
        $roleService = new UserService();
        $result = $roleService->getList($page,$per_page);
        if($result['status']==1){
            return layTableApi($result['data']['total'],$result['data']['data']);
        }else{
            return layTableApi(0,[],1);
        }
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
        return view('admin::user.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param AdminCreateRequest $request
     * @return \Illuminate\Http\Response
     */
    public function store(AdminCreateRequest $request)
    {
        //
        $data = $request->all();
        $data['uuid'] = \Faker\Provider\Uuid::uuid();
        $data['password'] = bcrypt($data['password']);
        Cache::forever('User', true);
        if (Admin::create($data)) {
            return redirect()->to(route('admin.user'))->with(['status' => '添加成功!']);
        }
        return redirect()->to(route('admin.user'))->withErrors('系统错误！');
    }

    /**
     * Display the specified resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function show()
    {
        //
        $user = Auth('admin')->user();
        return view('admin::user.detail', compact('user'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
        $user = Admin::findOrFail($id);
        return view('admin::user.edit', compact('user'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(AdminUpdateRequest $request, $id)
    {
        $user = Admin::findOrFail($id);
        $data = $request->except('password');
        Cache::forever('User', true);
        if ($request->get('password')) {
            $data['password'] = bcrypt($request->get('password'));
        }
        if ($user->update($data)) {
            return redirect()->to(route('admin.user'))->with(['status' => '编辑成功']);
        }
        return redirect()->to(route('admin.user'))->withErrors('系统错误！');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        //
        $ids = $request->get('ids');
        if (empty($ids)) {
            return apiResponse('请选择删除项目');
        }
        if (Admin::destroy($ids)) {
            return apiResponse('删除成功！',1,[]);
        }
        return apiResponse('系统异常');
    }

    public function role($id)
    {
        $user = Admin::findOrFail($id);
        $roles = Role::get();
        foreach($roles as $role) {
            $role->own = $user->hasRole($role) ? true : false;
        }
        return view('admin::user.role', compact('roles', 'user'));
    }

    public function assignRole(Request $request, $id)
    {
        $user = Admin::findOrFail($id);
        $roles = $request->get('roles', []);
        if ($user->syncRoles($roles)) {
            return redirect()->to(route('admin.user'))->with(['status' => '更新用户角色成功']);
        }
        return redirect()->to(route('admin.user'))->withErrors('系统错误！');
    }

    /**
     * 分配权限
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permission($id)
    {
        $user = Admin::findOrFail($id);
        $permissions = $this->permissionTree();
        foreach ($permissions as $key1 => $item1) {
            $permissions[$key1]['own'] = $user->hasDirectPermission($item1['id']) ? 'checked' : false;
            if (isset($item1['_child'])) {
                foreach ($item1['_child'] as $key2 => $item2) {
                    $permissions[$key1]['_child'][$key2]['own'] = $user->hasDirectPermission($item2['id']) ? 'checked' :false;
                    if (isset($item2['_child'])) {
                        foreach ($item2['_child'] as $key3 => $item3) {
                            $permissions[$key1]['_child'][$key2]['_child'][$key3]['own'] = $user->hasDirectPermission($item3['id']) ? 'checked' : false;
                        }
                    }
                }
            }
        }
        return view('admin::user.permission', compact('user', 'permissions'));
    }

    public function assignPermission(Request $request, $id)
    {
        $user = Admin::findOrFail($id);
        $permissions = $request->get('permissions');
        if (empty($permissions)) {
            $user->permissions()->detach();
            return redirect()->to(route('admin.user'))->with(['status' => '已更新用户直接权限，请刷新整个浏览器']);
        }
        $user->syncPermissions($permissions);
        return redirect()->to(route('admin.user'))->with(['status' => '已更新用户直接权限，请刷新整个浏览器']);
    }
}
